﻿using System;
using System.Collections.Generic;
using System.Text;

namespace cb0tServer
{
    class ChatHistory
    {
        private static List<ChatHistoryItem> buffer;

        public static void Init()
        {
            buffer = new List<ChatHistoryItem>();
        }

        public static void AddLine(String line)
        {
            buffer.Add(new ChatHistoryItem(line));

            if (buffer.Count > 25)
                buffer.RemoveAt(0);
        }

        public static void ViewHistory(UserObject userobj)
        {
            if (!Settings.allow_history)
                return;

            ChatHistoryItem[] history;

            if (userobj.level > 0)
                history = buffer.ToArray();
            else
                history = buffer.Count > 10 ? buffer.GetRange(buffer.Count - 11, 10).ToArray() : buffer.ToArray();

            uint time_now = Helpers.UnixTime();

            foreach (ChatHistoryItem line in history)
            {
                uint offset = (time_now - line.time);
                uint m;
                uint h;
                uint s;

                if (offset < 60)
                {
                    m = 0;
                    h = 0;
                    s = offset;
                }
                else
                {
                    if (offset >= 3600) // 1 hour
                    {
                        m = (uint)Math.Floor((double)offset / 60);
                        s = offset - (m * 60);
                        h = (uint)Math.Floor((double)m / 60);
                        m -= (h * 60);
                    }
                    else
                    {
                        m = (uint)Math.Floor((double)offset / 60);
                        s = offset - (m * 60);
                        h = 0;
                    }
                }

                String time = "\x000500\x000314-";
                time += (h >= 10) ? h.ToString() : ("0" + h);
                time += ":";
                time += (m >= 10) ? m.ToString() : ("0" + m);
                time += ":";
                time += (s >= 10) ? s.ToString() : ("0" + s);
                time += " \x000304";

                userobj.SendOutboundPacket(ServerOutboundPackets.AnnoucePacket(time + line.line));
            }

            if (history.Length > 0)
                userobj.SendOutboundPacket(ServerOutboundPackets.AnnoucePacket(StringTemplate.GetString(127)));
        }
    }

    class ChatHistoryItem
    {
        public String line;
        public uint time;

        public ChatHistoryItem(String line)
        {
            this.line = line;
            this.time = Helpers.UnixTime();
        }
    }
}
